"""
基金收益排行
http://vip.stock.finance.sina.com.cn/fund_center/index.html#hbphall
"""
import time
import random
import json
import requests
from config import config
from time_out import timelimited


@timelimited(15)
def get_url(type, period, top_num):
    """

    :param period: 'three_month', 'six_month', 'one_year', 'form_year'
    :param type: 0 全部; 2 股票; 1 混合;3  债券; 6  qdii
    :param top_num:
    :return:
    """
    sleep_time = random.randint(a=1, b=8)
    # print('begin sleep: {}'.format(sleep_time))
    time.sleep(sleep_time)

    url = config.sina_url.format(top_num, period, type)
    req = requests.get(url=url)
    if req.status_code == 200:
        html = req.text
        html = html.replace("/*<script>location.href='//sina.com';</script>*/",
                            '')
        html = html.replace("IO.XSRV2.CallbackList['abc'](", '')
        html = html[::-1][html[::-1].index(')') + 1:][::-1]

        return json.loads(html)
    return


def get_type_info(type, peroid_list, top_num=10):
    """

    :param type:
    :param peroid_list:
    :param top_num:
    :return:
    """
    code = set()
    for num, parameter in enumerate(peroid_list):
        try:
            data = get_url(period=parameter, top_num=top_num, type=type)
            if data and data.get('data'):
                codes = [data.get('symbol') for data in data.get('data')
                         if data.get('symbol')]
                codes = [str(code) for code in codes if str(code)[:2] != '15']
                if num == 0:
                    code = set(codes)
                else:
                    if len(codes) == 0 or len(code) == 0:
                        return None
                    else:
                        code = code & set(codes)
        except Exception as e:
            print('reqest url error: {}'.format(e))

    return list(code) if code else None


def sina_run(type, peroid_list, top_num):
    """

    :param type:
    :param peroid_list:
    :param top_num:
    :return:
    """
    code = get_type_info(type=type, peroid_list=peroid_list, top_num=top_num)
    return '；\t'.join(code) if code else '没有找到符合条件的基金'
